'use strict'
//获取控件
var userName = document.querySelector("input#username");
var inputRoom = document.querySelector("input#room");
var btnConnect = document.querySelector("button#connect");
var outputArea = document.querySelector("textarea#output");
var inputArea = document.querySelector("textarea#input");
var btnSend = document.querySelector("button#send");
var btnLeave = document.querySelector('button#leave');
//全局变量
var socket;
var room;
//事件处理
btnConnect.onclick = ()=> {
	//connect
	socket = io.connect();
	
	//recieve message
	socket.on("joined",(room,id) =>{
		console.log("INFOS-joined:Room--"+room+"  ID--"+id);
		btnConnect.disabled = true;
		btnLeave.disabled = false;
		inputArea.disabled = false;
		outputArea.disabled = false;
		btnSend.disabled = false;		
	});

	socket.on("leaved",(room,id) =>{
		console.log("INFOS-leaved:Room--"+room+"  ID--"+id);
		btnConnect.disabled = false;
		btnLeave.disabled = true;
		inputArea.disabled = true;
		btnSend.disabled = true;
		outputArea.disabled = true;
		socket.disconnect();		
	});

	socket.on("messages",(room,data,id) =>{
		console.log("INFOS-messages:Room--"+room+"  DATA--"+data);
		outputArea.value = outputArea.value + data + '\r';
	});

	socket.on('disconnect', (socket)=>{
		console.log("INFOS-disconnect:SOCKET--"+socket);
		btnConnect.disabled = false;
		btnLeave.disabled = true;
		inputArea.disabled = true;
		btnSend.disabled = true;
	});

	//send message	
	room = inputRoom.value;
	console.log("INFSO:EMIT-JOIN ROOM--"+room);
	socket.emit("join",room);
}

btnSend.onclick = () =>{
	var data = inputArea.value;
	data = userName.value + ":" + data;
	console.log("INFOS:EMIT-MESSAGE ROOM--"+room+"  DATA--"+data);
	socket.emit("message",room,data);	
	inputArea.value = '';
}
btnLeave.onclick = ()=>{
	room = inputRoom.value;
	console.log("INFOS:EMIT-LEAVE ROOM--"+room);
	socket.emit('leave', room);
}
inputArea.onkeypress = (event)=> {
        if (event.keyCode == 13) { 
	var data = inputArea.value;
	data = userName.value + ':' + data;
	console.log("INFOS:EMIT-MESSAGE ROOM--"+room+"  DATA--"+data);
	socket.emit('message', room, data);
	inputArea.value = '';
	event.preventDefault();
}}
